import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.table.*;

public class CopyOf_Kyssad_vazzad_paneel extends JPanel implements ActionListener {

	private static final long serialVersionUID = 1L;
	private boolean DEBUG = false;
	Kysimused kysimuste_database;
	Kysimus selectedQuestion = new Kysimus();
	JLabel kysimus, kysvastlabel, protsent;
	JComboBox teemadList;
	JButton vasta, j2rgmine, nullinupp, tyhi;
	JCheckBox[] tsekboxid;
	JLabel[] leibelid;
	JPanel[] vastuserida;
	JTable tabel;
	Object[][] kyssa_data;
	MyTableModel tabelimudel;
	ArrayList<JLabel> pildiNupp;
	String[] teemad = { "Tekst", "Matemaatika", "Majandus" }; // TODO teha
	boolean menyyNupudTehtud, gamemode;
	int count, kysimustearv, protsentarv, kyspikkus;
	double oiged;
	JPanel kysvast, vastapaneel;
	
	public CopyOf_Kyssad_vazzad_paneel(Kysimused kysimuste_data, boolean gamemode) {
		kysimuste_database = kysimuste_data;
		protsentarv = 0;
		oiged = 0;
		kysimustearv = 0;
		menyyNupudTehtud = false;
		this.gamemode = gamemode;
		setLayout(new BorderLayout());
		setBackground(new Color(191, 239, 255));
		lae_kysimuselabel();
		lae_tabel();
		
		lae_nupud();
		lae_skoori_paneel();
	}

	public void lae_kysimuselabel() {
		kysimus = new JLabel("" , JLabel.CENTER);
		// if(kysimus==null) kysimus = new JLabel(selectedQuestion .get_kysimus(),JLabel.CENTER);
		this.add(kysimus, BorderLayout.NORTH);
		kysimus.setBorder(BorderFactory.createLineBorder(Color.black));
		kysimus.setBackground(new Color(176, 226, 255));
		kysimus.setOpaque(true); /* */
	}
	
	public void lae_tabel() {
		//kyssa_data = { {"Mary", "Campione", "Snowboarding"} };
		tabelimudel = new MyTableModel();
		tabel = new JTable(tabelimudel);
		// tabel = new JTable(kyssa_data, new String[] {"K�simus", "Vastused", "Veel midagi"});
		tabel.setFillsViewportHeight(true);
		tabel.getColumnModel().getColumn(1).setPreferredWidth(20);
		TableColumn column = null;
		column = tabel.getColumnModel().getColumn(1);
		column.setPreferredWidth(20);
		tabel.doLayout();
		this.add(tabel, BorderLayout.CENTER);
	}
	
	/* public void lae_vastustepaneel() {
		vastustepaneel = new JPanel();
		vastustepaneel.setBorder(BorderFactory.createLineBorder(Color.pink));
		vastustepaneel.setLayout(new GridLayout(selectedQuestion.getHowManyAnswers(), 2));
	} */
	
	public void lae_nupud() {
		vastapaneel = new JPanel();
		vastapaneel.setLayout(new GridLayout(3, 1));
		vastapaneel.add(new JPanel());
		if (!this.gamemode) {
			nullinupp = new JButton("Nulli seis!");
			vastapaneel.add(nullinupp);
			nullinupp.addActionListener(this);
		}
		
		vasta = new JButton("VASTA!");
		vasta.addActionListener(this);
		vastapaneel.add(vasta);
		this.add(vastapaneel, BorderLayout.EAST);
		j2rgmine = new JButton("J2rgmine!");
		j2rgmine.addActionListener(this);
		this.add(j2rgmine, BorderLayout.SOUTH);
		j2rgmine.setEnabled(false);
	}
		
	public void lae_skoori_paneel() {
		kysvast = new JPanel();
		kysvast.setLayout(new GridLayout(2, 1));
		protsentarv = 0;
		kysvastlabel = new JLabel(oiged + " / " + kysimustearv);
		kysvastlabel.setBackground(new Color(255, 222, 173));
		kysvastlabel.setOpaque(true);
		protsent = new JLabel(protsentarv + " %");
		protsent.setBackground(new Color(255, 222, 173));
		protsent.setOpaque(true);
		kysvast.add(kysvastlabel);
		kysvast.add(protsent);
		this.add(kysvast, BorderLayout.WEST);
		kysvast.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
	}
	
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand() == "VASTA!") {
			kysimustearv += 1;
			vasta.setEnabled(false);
			j2rgmine.setEnabled(true);
			boolean kasutaja_kyik_yigesti = true;
			int yigesti_vastatud_lugeja = 0;
			boolean vastas_ainult_yigetele = true;
			
			for (int i = 0; i < selectedQuestion.getHowManyAnswers(); i++) {
				if (tabelimudel.getValueAt(i, 1).toString() == "true") {
					if (selectedQuestion.get_vastused().get(i).getVastus_kasoige()) 
						// kasutaja vastas selle konkreetse vastuse 6igesti
						yigesti_vastatud_lugeja++;
					else {
						vastas_ainult_yigetele= false;
						kasutaja_kyik_yigesti = false;
					}
				} else {
					if (selectedQuestion.get_vastused().get(i).getVastus_kasoige()) 
						kasutaja_kyik_yigesti = false;
				}
			} // end for
			
			double vastuse_eest_punkt=0;
			String ette = "";
			
			if (selectedQuestion.yigeid_vastuseid()== 0) {
				if (kasutaja_kyik_yigesti) {
					vastuse_eest_punkt = 1;
					ette = "Punkt " + vastuse_eest_punkt * 100 + " %  ";
				} else {
					vastuse_eest_punkt = 0;
					ette = "Punkt " + 0 + " %  ";
				}
			}
			else  {
				if (!kasutaja_kyik_yigesti) {
					if (selectedQuestion.yigeid_vastuseid()> 1) {
							if (vastas_ainult_yigetele) {
								vastuse_eest_punkt = (double) yigesti_vastatud_lugeja / (double) selectedQuestion.yigeid_vastuseid();
								ette = "Punkt " + vastuse_eest_punkt * 100 + " %  ";
							} 
							else {
								vastuse_eest_punkt = 0;
								ette = "Punkt " + 0 + " %  ";
							}
					} else {
						vastuse_eest_punkt = 0;
						ette = "Punkt " + 0 + " %  ";
					}					
				} else {
					vastuse_eest_punkt = yigesti_vastatud_lugeja / selectedQuestion.yigeid_vastuseid();
					ette = "Punkt " + vastuse_eest_punkt * 100 + " %  ";
				}
			}
			
			if (kasutaja_kyik_yigesti) {
				j2rgmine.setText(ette + "6ige, j2rgmine!");
				oiged = oiged + vastuse_eest_punkt;
			} else {
				if (vastuse_eest_punkt > 0) {
					ette = ette + "Osaliselt ";
				} 
				j2rgmine.setText(ette + "Vale :(  Kliki siia, et minna edasi");
				oiged = oiged + vastuse_eest_punkt;
			}

			/* for (int i = 0; i < selectedQuestion.getHowManyAnswers(); i++) {
				if (selectedQuestion.get_vastused().get(i).getVastus_kasoige())
					tabel   setBackground(new Color(200, 255, 200));
				else tabel setBackground(new Color(255, 200, 200));	
			} */
			try {
				protsentarv = (int) (oiged * 100 / kysimustearv);
			} catch (ArithmeticException o) {
				protsentarv = 0;
			}
			kysvastlabel.setText(oiged + " / " + kysimustearv);
			protsent.setText(protsentarv + " %");
		}
		if (e.getActionCommand().contains("6ige, j2rgmine!") || e.getActionCommand().contains( "Vale :(  Kliki siia, et minna edasi")) {
			j2rgmine.setText("J2rgmine!");
			count = 0;
			if (!this.gamemode) {					
					fortsykkel();
			} else {
				this.removeAll();
				this.repaint();
			}
		}
		if (e.getActionCommand() == "Nulli seis!") {
			oiged = 0;
			kysimustearv = 0;
			kysvastlabel.setText(oiged + " / " + kysimustearv);
			protsentarv = 0;
			protsent.setText(protsentarv + " %");
		}
		if (e.getActionCommand() == "removeAll") {
			this.removeAll();
			this.repaint();
		}
	}
	
	public void fortsykkel()  {

		selectedQuestion = kysimuste_database.getNextSuvaKyss();
		selectedQuestion.randomizeAnswers();
		System.out.println(selectedQuestion.getHowManyAnswers());
		tabelimudel.uus_data_ridade_arv(selectedQuestion.getHowManyAnswers());
		
		kysimus.setText("<html>" + selectedQuestion.get_kysimus() + "</html>");
		System.out.println(selectedQuestion.get_kysimus());
		kysimus.setFont(new Font("Arial",1,14));
		// vastustepaneel.setLayout(new GridLayout(selectedQuestion.getHowManyAnswers(), 2));
		// tsekboxid = new JCheckBox[selectedQuestion.getHowManyAnswers()];
		// leibelid = new JLabel[selectedQuestion.getHowManyAnswers()];
		// vastuserida = new JPanel[selectedQuestion.getHowManyAnswers()];

		for (int i = 0; i < selectedQuestion.getHowManyAnswers(); i++) {
			String vastusevariant = "<html>" + selectedQuestion.get_vastused().get(i).getVastuse_text() + "</html>";
			// System.out.println(kysimus);
			tabelimudel.setValueAt(vastusevariant, i, 0);
			tabelimudel.setValueAt(new Boolean(false), i, 1);
			
		}
		vasta.setEnabled(true);
		j2rgmine.setEnabled(false);
		this.repaint(); 
	}
	
	protected static ImageIcon annaIkoon(String asukoht) {
		if (asukoht != null) {
			return new ImageIcon(asukoht);
		} else {
			System.err.println("Ei leidnud faili: " + asukoht);
			return null;
		}
	}
	
	@SuppressWarnings("serial")
	public class MyTableModel extends AbstractTableModel {
        private String[] columnNames = { "Vastusevariandid",
                                        "�ige / Vale" };
        private Object[][] data = { {"Vastusevariant", new Boolean(true)} };
        //new Object[0][0];

        public void uus_data_ridade_arv (int read) {
        	System.out.println("KALA");
        	data = new Object[read][2];
        }
        
        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        /*
         * JTable uses this method to determine the default renderer/
         * editor for each cell.  If we didn't implement this method,
         * then the last column would contain text ("true"/"false"),
         * rather than a check box.
         */
        @SuppressWarnings("unchecked")
		public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        /*
         * Don't need to implement this method unless your table's
         * editable.
         */
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col < 1) {
                return false;
            } else {
                return true;
            }
        }

        /*
         * Don't need to implement this method unless your table's
         * data can change.
         */
        public void setValueAt(Object value, int row, int col) {
            if (DEBUG) {
                System.out.println("Setting value at " + row + "," + col
                                   + " to " + value
                                   + " (an instance of "
                                   + value.getClass() + ")");
            }

            data[row][col] = value;
            fireTableCellUpdated(row, col);

            if (DEBUG) {
                System.out.println("New value of data:");
                printDebugData();
            }
        }

        private void printDebugData() {
            int numRows = getRowCount();
            int numCols = getColumnCount();

            for (int i=0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j=0; j < numCols; j++) {
                    System.out.print("  " + data[i][j]);
                }
                System.out.println();
            }
            System.out.println("--------------------------");
        }
    }
}
